﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Mesuro.Common {
	public interface IChannelCollection : IEnumerable<IChannel> {
		IChannel this[string name] { get; }
		IChannel this[int idx] { get; }
		int Count { get; }
		/// <summary>
		/// 
		/// </summary>
		/// <param name="channel"></param>
		/// <returns>Index of the channel or -1 if the channel wasn't found</returns>
		int IndexOf( IChannel channel );
	}
	public class DefaultChannelCollection : IChannelCollection {
		//TODO: Replace this group of collections with a single tri-partite map (index-name-channel)
		private Dictionary<string, IChannel> _nameMap = new Dictionary<string, IChannel>();
		private List<IChannel> _idxMap = new List<IChannel>();

		public int Count { get { return _idxMap.Count; } }

		public IChannel this[string name] {
			get {
				IChannel chan;
				if (_nameMap.TryGetValue( name, out chan ))
					return chan;
				return null;
			}
		}

		public IChannel this[int idx] {
			get { return _idxMap[idx]; }
		}

		public void AddChannel( IChannel channel ) {
			_nameMap.Add( channel.Name, channel );
			_idxMap.Add( channel );
		}
		public void InsertChannel( int idx, IChannel channel ) {
			_nameMap.Add( channel.Name, channel );
			_idxMap.Insert( idx, channel );
		}
		public void ReplaceChannel( int idx, IChannel channel ) {
			_nameMap.Remove( this[idx].Name );
			_idxMap[idx] = channel;
			_nameMap.Add( channel.Name, channel );
		}

		public void Clear() {
			_nameMap.Clear();
			_idxMap.Clear();
		}

		public int IndexOf( IChannel channel ) {
			return _idxMap.IndexOf( channel );
		}

		public IEnumerator<IChannel> GetEnumerator() {
			return _idxMap.GetEnumerator();
		}

		System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
			return GetEnumerator();
		}

	}
}
